package com.farm.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.farm.pojo.SpiderData;
import com.farm.pojo.Vo.SpiderDataVo;
import com.farm.service.AnalyseService;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class AnalyseServiceImpl implements AnalyseService {

    @Override
    public String getYield(String requestPath) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet request = new HttpGet(requestPath);
        try {
            HttpResponse response = httpClient.execute(request);
            HttpEntity entity = response.getEntity();

            if (entity != null) {
                return EntityUtils.toString(entity);
            }
        } catch (Exception e) {
            return "网络异常";
        }
        return "网络异常";
    }

    @Override
    public String postYield(String requestPath,List<NameValuePair> urlParameters) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost postRequest = new HttpPost(requestPath);

        try {
            // 设置请求体
            postRequest.setEntity(new UrlEncodedFormEntity(urlParameters));

            // 发送请求并获取响应
            HttpResponse response = httpClient.execute(postRequest);
            HttpEntity entity = response.getEntity();

            if (entity != null) {
                return EntityUtils.toString(entity);
            }
        } catch (IOException e) {
            return "网络异常";
        } finally {
            // 关闭HttpClient
            try {
                httpClient.close();
            } catch (IOException e) {
                // 异常处理，日志记录等
            }
        }
        return "网络异常";
    }

    @Override
    public SpiderDataVo analyzeFish(String name,String specification) {
        try {
            String requestUrl = "http://www.xinfadi.com.cn/getPriceData.html"; // 请替换为你的API端点
            String formData = "limit=40&current=1&prodName=" + URLEncoder.encode(name, "UTF-8");
            URL url = new URL(requestUrl);
            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法和请求头
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("charset", "utf-8");
            connection.setDoOutput(true);

            // 将表单数据写入输出流
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = formData.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }

            // 读取响应
            try (BufferedReader br = new BufferedReader(
                    new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                StringBuilder response = new StringBuilder();
                String responseLine;
                while ((responseLine = br.readLine()) != null) {
                    response.append(responseLine.trim());
                }
                String res = response.toString();
                JSONObject jsonObject = JSONObject.parseObject(res);
                JSONArray list = jsonObject.getJSONArray("list");

                JSONObject o = (JSONObject)list.get(0);
                SpiderDataVo spiderDataVo = new SpiderDataVo(o.getString("prodName"),o.getString("specInfo"),o.getString("unitInfo"));
                List<Double> lowPrices = new LinkedList<>();
                List<Double> avgPrices = new LinkedList<>();
                List<Double> highPrices = new LinkedList<>();
                List<String> pubDates = new LinkedList<>();
                Double maxValue = Double.MIN_VALUE;
                Double minValue = Double.MAX_VALUE;
                list.stream().filter(item -> {
                            JSONObject jsonObject1 = (JSONObject) item;
                            return jsonObject1.get("specInfo").equals(specification);
                }).forEach(item->{
                    JSONObject data = (JSONObject)item;
                    Double lowPrice = Double.valueOf(data.getString("lowPrice"));
                    lowPrices.add(lowPrice);
                    avgPrices.add(Double.valueOf(data.getString("avgPrice")));
                    highPrices.add(Double.valueOf(data.getString("highPrice")));
                    pubDates.add(data.getString("pubDate").split(" ")[0]);
                });
               spiderDataVo.setLowestPrice(lowPrices);
               spiderDataVo.setAveragePrice(avgPrices);
               spiderDataVo.setHighestPrice(highPrices);
               spiderDataVo.setPublishTime(pubDates);
               for(Double d : lowPrices){
                   if(d.compareTo(minValue) < 0){
                       minValue = d;
                   }
               }

                for(Double d : highPrices){
                    if(d.compareTo(maxValue) > 0){
                        maxValue = d;
                    }
                }

                spiderDataVo.setMaxValue(maxValue);
                spiderDataVo.setMinValue(minValue);
               return spiderDataVo;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
